package com.xiaotu.LockDemo;

import com.sun.javafx.logging.PulseLogger;

/**
 * @Author xiaotu
 * @Description //TODO
 * @Date 2022/3/30 14:46
 * @ClassName TestPC
 * @Version 1.0
 * 生产者,消费者模型--->利用缓冲区解决:管程法
 **/
public class TestPC {
    public static void main(String[] args) {
        SynContainer synContainer = new SynContainer();
        new productor(synContainer).start();
        new consumer(synContainer).start();
    }
}
class productor extends Thread{
    SynContainer synContainer;
    public productor(SynContainer synContainer){
        this.synContainer = synContainer;
    }

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println("生产了第"+i+"只鸡");
            synContainer.push(new Chicken(i));
        }
    }
}
class consumer extends Thread{
    SynContainer synContainer;
    public consumer(SynContainer synContainer){
        this.synContainer = synContainer;
    }
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println("消费了第"+synContainer.pop().id+"只鸡");
        }
    }
}
class Chicken{
    public Integer id;
    public Chicken(Integer id){
        this.id = id;
    }
}
class SynContainer{
    //容器大小
    Chicken[] chickens = new Chicken[10];
    //容器计数器
    Integer count = 0;
    //生产者放入产品
    public synchronized  void push(Chicken chicken){
        //如果容器满了,就要等待消费者消费
        if(count==chickens.length){
            //通知消费者消费,生产者等待
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //如果容器没有满,就丢入产品
        chickens[count] = chicken;
        count++;
        System.out.println("=======>生产后容器大小"+count);
        //可以通知消费者消费了
        this.notifyAll();
    }
    //消费者消费产品
    public synchronized Chicken pop(){
        //判断能否消费
        if (count==0){
            //等待生产者生产,消费者等待
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //如果可以消费

        count--;
        Chicken chicken = chickens[count];
        System.out.println("=======>消费后容器大小"+count);
        //吃完以后,通知生产者生产
        this.notifyAll();
        return  chicken;
    }
}
